package com.headStorm.concurrent.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhangqq
 * @create 2021-07-13 15:39
 **/
public class ReadWriteLockDemo {
    private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
    private final Lock rlock = rwlock.readLock();
    private final Lock wlock = rwlock.writeLock();
    //private int[] counts = new int[10];
    private int num = 0;

    public void inc(int index) {
        wlock.lock(); // 加写锁
        try {
            num += 1;
        } finally {
            wlock.unlock(); // 释放写锁
        }
    }

    public int get() {
        rlock.lock(); // 加读锁
        try {
            return num;
        } finally {
            rlock.unlock(); // 释放读锁
        }
    }

    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newFixedThreadPool(5);
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true){
                    System.out.println(Thread.currentThread().getName());
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true){
                    System.out.println(Thread.currentThread().getName());
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
                readWriteLockDemo.inc(0);
            }
        });
    }
}
